let BASE_URL = 'http://localhost:8001/shop/';


function uuid() {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
 
    return s.join("");
}

document.write('<script type="text/javascript" src="../3thjs/crypto-js.js"></script>');

function aes_decrypt(encrypted) {
    let key = CryptoJS.enc.Latin1.parse('4550C11B2D10A7CD');
    let iv = CryptoJS.enc.Latin1.parse('7pcdd648c5680da4');

    //解密
    let decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv, padding: CryptoJS.pad.ZeroPadding});
    return decrypted.toString(CryptoJS.enc.Utf8);
}

function aes_encrypt(str) {
    let key = CryptoJS.enc.Latin1.parse('4550C11B2D10A7CD');
    let iv = CryptoJS.enc.Latin1.parse('7pcdd648c5680da4');

    //加密
    let encrypted = CryptoJS.AES.encrypt(str, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    });
    return encrypted.toString();
}

function gen_client_key(callback) {
    if (getLocalStorage('session_id', 'null') === 'null') {
        localStorage['session_id'] = uuid();
    }
    let keySize = 512;
    // 一次一密, 密钥协商
    // 1. 生成RSA
    let crypt = new JSEncrypt({default_key_size: keySize});

    crypt.getKey();
    let pubKey = crypt.getPublicKey();
    // console.log('privateKey: ' + crypt.getPrivateKey());
    // console.log('publicKey: ' + pubKey);

    doPost({
        url: 'web/security/request_pk',
        data: {
            step: 1,
        },
        callback: function (res) {
            if (res.data.code !== 1) {
                callback(false, res);
                return;
            }
            // console.log(res);
            let pk = res.data.data.key;
            pk = window.atob(pk);
            // console.log('pk', pk);
            pk = pk.replace(/\\n/g, String.fromCharCode(10));
            // console.log('pk', pk);
            let tt = new JSEncrypt({default_key_size: 2048});
            tt.setPublicKey(pk);
            let sendKey = tt.encrypt(pubKey);
            // console.log(sendKey);
            doPost({
                url: 'web/security/request_pk',
                data: {
                    step: 2,
                    pk: sendKey,
                },
                callback: function (res) {
                    if (res.data.code !== 1) {
                        callback(false, res);
                        return;
                    }
                    let content = res.data.data.key;
                    let aesKey = crypt.decrypt(content);
                    callback(true, aesKey);
                }
            }, false);
        }
    }, false);
}


function doGet(entity, showProgress = true) {
    if (showProgress) {
        showProgressTip();
    }
    if (entity.data && Object.keys(entity.data).length > 0) {
        entity.url += '?';
        for (let k of Object.keys(entity.data)) {
            entity.url += k + '=' + entity.data[k] + '&';
        }
        entity.url = entity.url.substring(0, entity.url.length - 1);
    }
    entity.url = BASE_URL + entity.url;

    axios({
        url: entity.url,
        method: 'get',
        transformRequest: [function (data) {
            let ret = '';
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
            }
            return ret;
        }],
        headers: {
            'session_id': getLocalStorage('session_id', 'null'),
        }

    }).then((res) => {
        if (showProgress) {
            hideProgressTip();
        }
        log(entity, res);
        if (res.data.code === -1) {
            window.parent.location.href = BASE_URL + 'web/static/html/login.html';
        } else {
            entity.callback(res);
        }
    }).catch(error => {
        if (showProgress) {
            hideProgressTip();
        }
        log(entity, error);
        // entity.callback({
        //     data: {
        //         code: 0,
        //         msg: error,
        //     }
        // });
    });
}

function doPost(entity, showProgress = true) {
    if (showProgress) {
        showProgressTip();
    }
    let data = entity.data;
    let iv = CryptoJS.enc.Latin1.parse('iR9hPO63zXohlw2p');

    if (entity.url.indexOf('web/security/request_pk') < 0) {
        let key = getLocalStorage('k', 'null');

        if (key === 'null') {
            window.parent.location.href = BASE_URL + 'web/static/html/login.html';
            return;
        } else {
            window.e = CryptoJS.AES.decrypt(key, 'c15be48e6ed89c6748c6aebe6d3d5e65', {
                iv: iv,
                padding: CryptoJS.pad.ZeroPadding
            }).toString(CryptoJS.enc.Utf8);
        }

        let param = JSON.stringify(entity.data);
        key = CryptoJS.enc.Latin1.parse(window.e);

        //加密
        let content = CryptoJS.AES.encrypt(param, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.ZeroPadding
        }).toString();
        data = {
            c: content,
        };
    }

    entity.url = BASE_URL + entity.url;

    axios({
        url: entity.url,
        method: 'post',
        data: data,
        transformRequest: [function (data) {
            let ret = '';
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
            }
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'session_id': getLocalStorage('session_id', 'null'),
        }

    }).then((res) => {
        if (showProgress) {
            hideProgressTip();
        }
        log(entity, res);
        if (res.data.code === -1) {
            window.parent.location.href = BASE_URL + 'web/static/html/login.html';
        } else {
            entity.callback(res);
        }

    }).catch(error => {
        if (showProgress) {
            hideProgressTip();
        }
        log(entity, error);
        // entity.callback({
        //     data: {
        //         code: 0,
        //         msg: '网络错误',
        //     }
        // });
    });
}


function downloadFile(url, callback) {
    showProgressTip();
    let fileType = url.split(".").pop();
    let fileName = new Date().toLocaleString() + '.' + fileType;
    axios({
        url: BASE_URL + url,
        method: 'get',
        responseType: 'blob',

    }).then((res) => {
        hideProgressTip();
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();

        callback(res);
    }).catch(error => {
        hideProgressTip();
        callback(error);
    });
}

function uploadFile(url, file, callback) {
    if (file === undefined) {
        callback({
            data: {
                code: 0,
                msg: 'file is not found'
            }
        });
        return;
    }
    let param = new FormData();
    param.append('file', file);
    showProgressTip();
    axios({
        url: BASE_URL + url,
        method: 'post',
        data: param,
        headers: {
            'Content-Type': 'multipart/form-data',
        }

    }).then((res) => {
        hideProgressTip();
        if (res.data.code === -1) {
            window.parent.location.href = BASE_URL + 'web/static/html/login.html';
        } else {
            callback(res);
        }

    }).catch(error => {
        hideProgressTip();
        callback({
            data: {
                code: 0,
                msg: error,
            }
        });
    });
}

function uploadFileWithParams(url, file, params, callback) {
    if (file === undefined) {
        callback({
            data: {
                code: 0,
                msg: 'file is not found'
            }
        });
        return;
    }
    let param = new FormData();
    param.append('file', file);
    let keys = Object.keys(params);
    for (let i = 0; i < keys.length; i++) {
        param.append(keys[i], params[keys[i]]);
    }
    showProgressTip();
    axios({
        url: url,
        method: 'post',
        data: param,
        headers: {
            'Content-Type': 'multipart/form-data',
        }

    }).then((res) => {
        hideProgressTip();
        if (res.data.code === -1) {
            window.parent.location.href = BASE_URL + 'web/static/html/login.html';
        } else {
            callback(res);
        }

    }).catch(error => {
        hideProgressTip();
        callback({
            data: {
                code: 0,
                msg: error,
            }
        });
    });
}


function showSuccess(duration = 2000) {
    setTimeout(() => {
        $('#alert-success')[0].style.visibility = 'visible';
        setTimeout(function () {
            $('#alert-success')[0].style.visibility = 'hidden';
        }, duration);
    }, 400);
}

function showFail(duration = 2000) {
    setTimeout(() => {
        $('#alert-fail')[0].style.visibility = 'visible';
        setTimeout(function () {
            $('#alert-fail')[0].style.visibility = 'hidden';
        }, duration);
    }, 400);
}

function showInfo(info, duration = 2000) {
    setTimeout(() => {
        infoVue.info = info;
        $('#alert-info')[0].style.visibility = 'visible';
        setTimeout(function () {
            $('#alert-info')[0].style.visibility = 'hidden';
        }, duration);
    }, 400);
}

function showTip(info) {
    infoVue.info = info;
    $('#alert-tip')[0].style.visibility = 'visible';
}

function hideTip() {
    $('#alert-tip')[0].style.visibility = 'hidden';
}

function log(...args) {
    for (let i = 0; i < args.length; i++) {
        console.log(args[i]);
    }
}


function getQueryVariable(key, defaultValue = undefined) {
    let query = window.location.search.substring(1);
    let lets = query.split("&");
    for (let i = 0; i < lets.length; i++) {
        let pair = lets[i].split("=");
        if (pair[0] === key) {
            return pair[1];
        }
    }
    return defaultValue;
}

function getLocalStorage(key, defaultValue) {
    let value = localStorage[key];
    if (value === undefined || value === null) {
        return defaultValue;
    } else {
        return value;
    }
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

function showProgressTip() {
    try {
        let tip = document.getElementById('my-progress');
        if (tip === null || tip === undefined) {
            window.parent.showProgressTip();
        } else {
            tip.style.visibility = "visible";
            let value = parseInt(tip.attributes['releaseCount'].value);
            value += 1;
            tip.attributes['releaseCount'].value = value;
        }
    } catch (e) {
        // log(e)
    }
}

function hideProgressTip() {
    try {
        let tip = document.getElementById('my-progress');
        if (tip) {
            let value = parseInt(tip.attributes['releaseCount'].value);
            value -= 1;
            if (value < 0) {
                value = 0;
            }
            tip.attributes['releaseCount'].value = value;
            if (value === 0) {
                tip.style.visibility = "hidden";
            }
        } else {
            window.parent.hideProgressTip();
        }
    } catch (e) {
    }
    setTimeout(function () {
        updateSelectableStyle();
    }, 6);
}

function updateSelectableStyle() {
    let rows = $('[selectable="true"]');
    for (let i = 0; i < rows.length; i++) {
        let parentNode = rows[i].parentNode.parentNode;
        rows[i].onclick = function (evt) {
            for (let j = 0; j < rows.length; j++) {
                if (rows[j].parentNode.parentNode === parentNode) {
                    rows[j].style.background = null;
                }
            }
            rows[i].style.background = '#EFF0F3';
        };
    }
}


function browserType() {
    let explorer = window.navigator.userAgent;
    //判断是否为IE浏览器
    if (explorer.indexOf("MSIE") >= 0) {
        return 'ie';
    }
    //判断是否为Firefox浏览器
    else if (explorer.indexOf("Firefox") >= 0) {
        return 'Firefox';
    }
    //判断是否为Chrome浏览器
    else if (explorer.indexOf("Chrome") >= 0) {
        return 'Chrome';
    }
    //判断是否为Opera浏览器
    else if (explorer.indexOf("Opera") >= 0) {
        return 'Opera';
    }
    //判断是否为Safari浏览器
    else if (explorer.indexOf("Safari") >= 0) {
        return 'Safari';
    }
}

function updateCheckboxStyle() {
    $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green',
    }).on('ifChecked ifUnchecked', function () {
        $(this)[0].dispatchEvent(new Event("change"));
    });
}

let preKey = '';
document.onkeydown = function (event) {
    let e = event || window.event || arguments.callee.caller.arguments[0];
    if (e.key === 'Alt') {
        preKey = 'Alt';
    } else if (e.key === '∑' || e.key === 'w' && preKey === 'Alt') {
        if (window.navigationVue !== undefined) {
            window.navigationVue.close();
        } else {
            window.parent.navigationVue.close();
        }
    } else {
        preKey = '';
    }
};


Array.prototype.indexOf = function (val) {
    for (let i = 0; i < this.length; i++) {
        if (this[i] === val) return i;
    }
    return -1;
};

Array.prototype.remove = function (val) {
    let index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
    return index;
};

Array.prototype.removeAt = function (index) {
    if (index > -1) {
        this.splice(index, 1);
    }
};

Array.prototype.clear = function () {
    this.length = 0;
};

Array.prototype.clone = function () {
    return this.slice(0);
};

Array.prototype.subarray = function (start, end) {
    let tmp = this.slice(0);
    return tmp.slice(start, end);
};

function includeHTML(html, callback = undefined) {
    // callback = function(code, msg){}
    if (callback) {
        let js = 'window.' + html + ' = callback';
        eval(js);
    }
    html += '.html';
    let z, i, elmnt, file, xhttp;
    z = document.getElementsByTagName("*");
    for (i = 0; i < z.length; i++) {
        elmnt = z[i];
        file = elmnt.getAttribute("include");
        if (file === html) {
            let onload = elmnt.getAttribute('onload');
            xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState === 4) {
                    if (this.status === 200) {
                        try {
                            elmnt.innerHTML = this.responseText;
                            let str = this.responseText.match(/<script type="text\/javascript">([\s\S]*)<\/script>/);
                            if (str) {
                                if (str.length > 1) {
                                    eval(str[1]);
                                }
                            }
                            str = this.responseText.match(/<script>([\s\S]*)<\/script>/);
                            if (str) {
                                if (str.length > 1) {
                                    eval(str[1]);
                                }
                            }
                            if (onload) {
                                eval(onload);
                            }
                        } catch (err) {
                            if (callback) {
                                callback(-1, err)
                            }
                        }
                    }
                    if (this.status === 404) {
                        elmnt.innerHTML = "Page not found.";
                        if (callback) {
                            callback(this.status, "Page not found. File: " + file);
                        }
                    }
                    elmnt.removeAttribute("include");
                }
            };
            xhttp.open("GET", file, true);
            xhttp.send();
            return;
        }
    }
}

Date.prototype.format = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};
